<!DOCTYPE html>
<html lang="en">

<head>
	<meta charset="UTF-8">
	<meta name="viewport" content="width=device-width, initial-scale=1.0">
	<title>2462. 雇佣 K 位工人的总代价</title>
</head>

<body>
  https://leetcode.cn/problems/total-cost-to-hire-k-workers/description/?envType=daily-question&envId=2024-05-01
</body>

<script>
  /**
   * @param {number[]} costs
   * @param {number} k
   * @param {number} candidates
   * @return {number}
   */
  var totalCost = function (costs, k, candidates) {

    let total = 0;

    // let indexArr = []
    let findIndex = null;

    let endList = null;
    let startList = null

    if (costs.length > candidates * 2) {
      endList = costs.splice(costs.length - candidates, costs.length);
      startList = costs.splice(0, candidates);
    }

    for (i = 0; i < k; i++) {
      // debugger
      if (endList && startList) {
        let startMin = Math.min(...startList);
        let endMin = Math.min(...endList);

        if (startMin <= endMin) {
          findIndex = startList.indexOf(startMin);
          findVal = startList.splice(findIndex, 1)[0];
          if (costs && costs.length) startList.push(costs.shift())
        } else {
          findIndex = endList.indexOf(endMin);
          findVal = endList.splice(findIndex, 1)[0];
          if (costs && costs.length) endList.unshift(costs.pop())
        }

        if (!costs.length) {
          costs = [...startList, ...endList];
          startList = null;
          endList = null;
        }
      } else {
        if (costs.length === 0) return total;
        findIndex = costs.indexOf(Math.min(...costs));
        findVal = costs.splice(findIndex, 1)[0];
      }

      total += findVal;
    }

    return total;
  };

  // let res = totalCost([17, 12, 10, 2, 7, 2, 11, 20, 8], 3, 4);
  // let res = totalCost([2, 2, 2, 2, 1, 2, 2, 2, 2], 9, 2);
  let res = totalCost([31, 25, 72, 79, 74, 65, 84, 91, 18, 59, 27, 9, 81, 33, 17, 58], 11, 2);
  console.log(res)
</script>

</html>
